<template>
  <div class="training-class-page">
    <div class="page-header">
      <h2>培训班学员进出班管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleRefresh">刷新</el-button>
        <el-button @click="handleBack">返回 班级学员</el-button>
      </div>
    </div>

    <!-- 学员管理子组件 -->
    <training-student-management
      :class-info="classInfo"
      :student-pool="studentPool"
      :entered-students="enteredStudents"
      @student-enter="handleStudentEnter"
      @students-batch-enter="handleStudentsBatchEnter"
      @student-exit="handleStudentExit"
      @students-batch-exit="handleStudentsBatchExit"
      @manage-student="handleManageStudent"
      @project-changed="handleProjectChange"
      @student-search="handleStudentSearch"
    ></training-student-management>

    <!-- 学员管理弹窗 -->
    <el-dialog
      title="学员管理"
      :visible.sync="studentManageDialogVisible"
      width="600px"
    >
      <div v-if="currentStudent" class="student-detail">
        <el-form label-width="100px" :model="currentStudent" disabled>
          <el-form-item label="姓名">
            <el-input v-model="currentStudent.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="currentStudent.idCard" disabled></el-input>
          </el-form-item>
          <el-form-item label="培训专业">
            <el-input v-model="currentStudent.trainingMajor" disabled></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="currentStudent.gender" disabled>
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" disabled>
            <el-input v-model="currentStudent.age" type="number"></el-input>
          </el-form-item>
          <el-form-item label="电话" disabled>
            <el-input v-model="currentStudent.phone"></el-input>
          </el-form-item>
          <!-- <el-form-item label="单位">
            <el-input v-model="currentStudent.company"></el-input>
          </el-form-item> -->
          <el-form-item label="缴费状态" v-if="currentStudent.feeStatus" disabled>
            <el-select v-model="currentStudent.feeStatus">
              <el-option label="已缴费" value="已缴费"></el-option>
              <el-option label="未缴费" value="未缴费"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资料状态" v-if="currentStudent.docStatus" disabled>
            <el-select v-model="currentStudent.docStatus">
              <el-option label="资料通过" value="资料通过"></el-option>
              <el-option label="资料未通过" value="资料未通过"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资料缺项" v-if="currentStudent.docLack !== undefined" disabled>
            <el-input v-model="currentStudent.docLack" type="textarea"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <!-- <el-button @click="studentManageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudentInfo">保存</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TrainingStudentManagement from './TrainingStudentManagement.vue';
import {
  registrationList,
} from "@/api/training/registration";
import {
  getInfoByTrainingClassId,
} from "@/api/training/TrainingClass";
import {
  batchJoin, getClassStudents,
} from "@/api/training/ClassStudent";
import { batchQuit } from "@/api/training/ClassStudent";
import { projectTreeSelect } from "@/api/training/projects";

export default {
  name: 'TrainingClassPage',
  components: {
    TrainingStudentManagement
  },
  data() {
    return {
      // 参数
      classId: "",
      className: "",
      handoverStatus: "",
      projectId: "",
      trainingClassCode: "",
      classStatus: "",
      loading: false,
      total: 0,

      // 班级信息
      classInfo: [],

      // 学员报名库
      projectOptions: [],
      projectMap: new Map(),
      studentPool: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idNumber: null,
        certNumber: null,
        trainingType: null,
        phonenumber: null,
        unitName: null,
        paymentStatus: null,
        recordStatus: null,
        submitStatus: null,
        startTime: null,
        endTime: null,
        projectId: null, // 用于接收树节点选中值
      },

      // 进班学员列表
      enteredStudents: [],

      // 学员管理弹窗
      studentManageDialogVisible: false,
      currentStudent: null
    };
  },
  created() {
    // 调整顺序，确保项目树先加载完成
    this.loadProjectTree().then(() => {
      this.getInfoByTrainingClassId();
      this.getClassStudent(this.classId).then(() => {
        // 班级学员加载完成后再加载报名库
        this.getRegistrationInfo(this.projectId);
      });
    });
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId
        this.className = params.className
        this.handoverStatus = params.handoverStatus
        this.projectId = params.projectId
        this.trainingClassCode = params.trainingClassCode
      }
    }
  },
  methods: {
    async getClassStudent(id) {
      if (!id) return; // 确保id存在

      try {
        const res = await getClassStudents({
          trainingClassId: id,
        });

        if (res.code === 200 && res.rows && res.rows.length > 0) {
          // 适配后端数据到enteredStudents格式
          this.enteredStudents = res.rows.map(item => this.adaptEnteredStudent(item.registrationDto));

          // 过滤学员报名库，移除已进班的学员
          this.filterStudentPool();

        } else {
          this.enteredStudents = []; // 如果没有数据，清空进班学员列表
        }
      } catch (error) {
        console.error('获取班级学员失败:', error);
      }
    },

    // 适配后端registrationDto到enteredStudents格式
    adaptEnteredStudent(registrationDto) {
    console.log(registrationDto)
      return {
        id: registrationDto.registrationId,
        name: registrationDto.studentName || '未知',
        idCard: registrationDto.idNumber || '',
        trainingMajor: this.getTrainingMajor(registrationDto.projectId),
        gender: this.getGenderText(registrationDto.sex),
        age: this.calculateAge(registrationDto),
        phone: registrationDto.phonenumber || '',
        company: registrationDto.unitName || '',
        registerDate: this.formatDate(registrationDto.createTime) || '',
        feeStatus: this.mapPaymentStatus(registrationDto.paymentStatus),
        docStatus: this.mapRecordStatus(registrationDto.recordStatus),
        docLack: registrationDto.recordMissing || '',
        studentId: registrationDto.studentId
      };
    },

    // 过滤学员报名库，移除已进班的学员
    filterStudentPool() {
      if (!this.studentPool || this.studentPool.length === 0) return;

      // 获取所有已进班学员的身份证号
      const enteredIdCards = this.enteredStudents.map(student => student.idCard);

      // 过滤掉已进班的学员
      this.studentPool = this.studentPool.filter(student =>
        !enteredIdCards.includes(student.idCard)
      );
    },

    // 映射缴费状态
    mapPaymentStatus(status) {
      const statusMap = {
        '0': '未缴费',
        '1': '已缴费',
      };
      return statusMap[status] || '未知';
    },

    // 映射资料状态
    mapRecordStatus(status) {
      const statusMap = {
        '0': '资料未通过',
        '1': '资料通过',
      };
      return statusMap[status] || '未知';
    },

    // 获取培训班vo详细信息
    async getInfoByTrainingClassId() {
      const res = await getInfoByTrainingClassId(this.classId);
      if (res.code === 200) {
        this.classInfo = this.adaptClassInfo(res.data);
      }
    },

    // 获取项目树
    async loadProjectTree() {
      try {
        const res = await projectTreeSelect({});
        this.projectOptions = res.data;
        this.initProjectMap(this.projectOptions);
        return Promise.resolve();
      } catch (error) {
        console.error('加载项目树失败:', error);
        return Promise.reject(error);
      }
    },

    // 初始化项目映射
    initProjectMap(treeData) {
      this.projectMap.clear();
      this.buildProjectMap(treeData);
    },

    // 递归构建映射
    buildProjectMap(treeData) {
      for (const item of treeData) {
        this.projectMap.set(item.id, item.label);
        if (item.children && item.children.length > 0) {
          this.buildProjectMap(item.children);
        }
      }
    },

    // 获取报名库信息
    async getRegistrationInfo(projectId) {
      this.queryParams.projectId = projectId;
      this.queryParams.pageNum = 1;
      await this.getList();
      // 报名库数据加载完成后过滤已进班学员
      this.filterStudentPool();
    },

    // 查询列表
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      return registrationList(params).then((response) => {
        this.total = response.total;
        // 数据适配
        this.studentPool = this.adaptRegistrationData(response.rows);
        this.loading = false;
        return Promise.resolve();
      }).catch(error => {
        console.error('获取列表失败:', error);
        this.loading = false;
        return Promise.reject(error);
      });
    },

    // 数据适配
    adaptRegistrationData(registrationList) {
      return registrationList.map(item => {
        return {
          id: item.registrationId,
          name: item.studentName || '未知',
          idCard: item.idNumber || '',
          trainingMajor: this.getTrainingMajor(item.projectId),
          gender: this.getGenderText(item.sex),
          age: this.calculateAge(item),
          phone: item.phonenumber || '',
          company: item.unitName || '',
          applyDate: this.formatDate(item.createTime) || '',
          studentId: item.studentId,
          paymentStatus: item.paymentStatus,
          recordStatus: item.recordStatus,
          registerDate: this.formatDate(new Date()),
          feeStatus: this.mapPaymentStatus(item.paymentStatus || '0'),
          docStatus: this.mapRecordStatus(item.recordStatus || '0')
        };
      });
    },

    // 获取培训专业名称
    getTrainingMajor(projectId) {
      if (!projectId) return '未知专业';
      return this.projectMap.get(projectId) || '未知专业';
    },

    // 计算年龄
    calculateAge(item) {
      if (item.birthDate) {
        return this.calculateAgeFromDate(item.birthDate);
      } else if (item.idNumber && item.idNumber.length === 18) {
        return this.calculateAgeFromIdCard(item.idNumber);
      }
      return 0;
    },

    // 从日期计算年龄
    calculateAgeFromDate(birthDate) {
      const birth = new Date(birthDate);
      const today = new Date();
      let age = today.getFullYear() - birth.getFullYear();
      const monthDiff = today.getMonth() - birth.getMonth();

      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
      }
      return age;
    },

    // 从身份证计算年龄
    calculateAgeFromIdCard(idCard) {
      const birthStr = idCard.substring(6, 14);
      const birthDate = `${birthStr.substring(0,4)}-${birthStr.substring(4,6)}-${birthStr.substring(6,8)}`;
      return this.calculateAgeFromDate(birthDate);
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 转换性别文本
    getGenderText(sex) {
      const genderMap = {
        '0': '男',
        '1': '女',
        '男': '男',
        '女': '女',
        'M': '男',
        'F': '女',
      };
      return genderMap[sex] || '未知';
    },

    // 数据适配函数
    adaptClassInfo(backendData) {
      return [
        { label: '培训专业', value: backendData.trainingProjectName || '--' },
        { label: '年度', value: backendData.trainingYear || '--' },
        { label: '培训类别', value: this.mapTrainingType(backendData.trainingType) },
        { label: '期次', value: backendData.trainingSession || '--' },
        { label: '培训类型', value: this.mapStartupType(backendData.startupType) },
        { label: '开班类型', value: backendData.startupTypeName || '--' },
        { label: '培训班编号', value: backendData.trainingClassCode || '--' },
        { label: '培训班名称', value: backendData.trainingClassName || '--' },
        { label: '培训部门', value: backendData.trainingDepartmentName || '--' },
        { label: '开始日期', value: backendData.startDate || '--' },
        { label: '结束日期', value: backendData.endDate || '--' },
        { label: '班主任', value: backendData.headTeacher1Name || '--' },
        { label: '培训地区', value: backendData.trainingRegion || '--' },
        { label: '培训地点', value: backendData.trainingAddress || '--' },
        {
          label: '班级状态',
          value: backendData.classStatusName || '--',
          className: this.mapClassStatusStyle(backendData.classStatus)
        },
        {
          label: '发布状态',
          value: this.mapHandoverStatus(backendData.handoverStatus),
          className: this.mapHandoverStatusStyle(backendData.handoverStatus)
        },
        { label: '招收人数', value: backendData.totalQuota?.toString() || '0' },
        {
          label: '注册人数',
          value: backendData.registeredCount?.toString() || '0',
          className: this.mapRegisteredCountStyle(backendData.registeredCount, backendData.totalQuota)
        },
        { label: '创建人', value: backendData.createBy || '--' },
        { label: '创建日期', value: backendData.createTime || '--' }
      ];
    },

    // 映射培训类别
    mapTrainingType(type) {
      const typeMap = {
        '1': '新训',
        '2': '复训',
        '3': '继续教育'
      };
      return typeMap[type] || '未知';
    },

    // 映射开班类型
    mapStartupType(type) {
      const typeMap = {
        '1': '经营性培训',
        '2': '线上开班'
      };
      return typeMap[type] || '未知';
    },

    // 映射班级状态样式
    mapClassStatusStyle(status) {
      const styleMap = {
        '0': 'status-draft', // 草稿
        '1': 'status-pending', // 待开始
        '2': 'status-opening', // 培训中
        '3': 'status-completed' // 已完成
      };
      return styleMap[status] || '';
    },

    // 映射交接状态
    mapHandoverStatus(status) {
      const statusMap = {
        '0': '未发布',
        '1': '已发布',
        '2': '已交接'
      };
      return statusMap[status] || '未知';
    },

    // 映射交接状态样式
    mapHandoverStatusStyle(status) {
      const styleMap = {
        '0': 'status-draft',
        '1': 'status-published',
        '2': 'status-handed'
      };
      return styleMap[status] || '';
    },

    // 映射注册人数样式
    mapRegisteredCountStyle(registered, total) {
      if (registered >= total) {
        return 'status-full';
      } else if (registered > total * 0.8) {
        return 'status-almost-full';
      } else {
        return 'status-available';
      }
    },

    // 刷新数据
    handleRefresh() {
      this.loadProjectTree().then(() => {
        this.getInfoByTrainingClassId();
        this.getClassStudent(this.classId).then(() => {
          this.getRegistrationInfo(this.projectId);
        });
      });
      this.$message.success('数据已刷新');
    },

    // 返回列表
    handleBack() {
      // 准备要传递的数据
      const paramsData = {
        className: this.className,
        classId: this.classId,
        handoverStatus: this.handoverStatus,
        trainingClassCode: this.trainingClassCode,
        projectId:this.projectId,
      }
      console.log(paramsData)

      // 加密参数
      // const encryptedParams = encrypt(paramsData)

      this.$router.push({
        name: '班级学员',
        params: paramsData
      });
    },

    // 处理“培训项目变更”事件
    handleProjectChange({ projectId, searchQuery }) {
      this.getRegistrationInfo(projectId);
    },

    // 处理“学员搜索”事件
    handleStudentSearch({ query, projectId }) {
      if (!query) {
        this.getRegistrationInfo(this.projectId);
        return;
      }

      // 对姓名进行模糊搜索
      let filteredStudentPool = this.studentPool.filter(student =>
        student.name && student.name.includes(query)
      );
      this.studentPool = filteredStudentPool;
    },

    // 单个学员进班
    async handleStudentEnter(student) {
      this.$confirm(`确定让学员 ${student.name} 进班？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 构造接口所需参数
          const classStudentList = [
            {
              trainingClassId: this.classId,
              studentId: student.studentId,
              registrationId: student.id,
            }
          ];

          // 调用批量进班接口（支持单个）
          const result = await batchJoin(classStudentList);

          if (result.code === 200) {
            // 从报名库移除
            const index = this.studentPool.findIndex(item => item.id === student.id);
            if (index !== -1) {
              this.studentPool.splice(index, 1);
            }

            // 添加到进班列表
            this.enteredStudents.push({
              ...student,
              // 补充进班时需要的额外信息
              registerDate: this.formatDate(new Date()),
              feeStatus: this.mapPaymentStatus(student.paymentStatus || '0'),
              docStatus: this.mapRecordStatus(student.recordStatus || '0')
            });

            this.$message.success(`学员 ${student.name} 已成功进班`);
          } else {
            this.$message.error(result.msg || '进班操作失败');
          }
        } catch (error) {
          console.error('进班操作出错:', error);
          this.$message.error('进班操作失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消进班操作');
      });
    },

    // 批量学员进班
    async handleStudentsBatchEnter(students) {
      if (!students || students.length === 0) return;

      this.$confirm(`确定让选中的 ${students.length} 名学员进班？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 构造接口所需参数数组
          const classStudentList = students.map(student => ({
            trainingClassId: this.classId,
            studentId: student.studentId,
            registrationId: student.id,
          }));

          // 调用批量进班接口
          const result = await batchJoin(classStudentList);

          if (result.code === 200) {
            // 处理进班成功的学员
            students.forEach(student => {
              // 从报名库移除
              const index = this.studentPool.findIndex(item => item.id === student.id);
              if (index !== -1) {
                this.studentPool.splice(index, 1);
              }

              // 添加到进班列表
              this.enteredStudents.push({
                ...student,
                registerDate: this.formatDate(new Date()),
                feeStatus: this.mapPaymentStatus(student.paymentStatus || '0'),
                docStatus: this.mapRecordStatus(student.recordStatus || '0')
              });
            });

            this.$message.success(`成功安排 ${students.length} 名学员进班`);
          } else {
            this.$message.error(result.msg || '批量进班操作失败');
          }
        } catch (error) {
          console.error('批量进班操作出错:', error);
          this.$message.error('批量进班操作失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消批量进班操作');
      });
    },

    // 单个学员退班
    async handleStudentExit(student) {
      this.$confirm(`确定让学员 ${student.name} 退班？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 构造接口所需参数
          const classStudentList = [
            {
              trainingClassId: this.classId,
              studentId: student.studentId,
              registrationId: student.id,
            }
          ];

          // 调用批量退班接口（支持单个）
          const result = await batchQuit(classStudentList);

          if (result.code === 200) {
            // 从进班列表移除
            const index = this.enteredStudents.findIndex(item => item.id === student.id);
            if (index !== -1) {
              this.enteredStudents.splice(index, 1);
            }

            // 添加到报名库
            const simplifiedStudent = {
              id: student.id,
              name: student.name,
              idCard: student.idCard,
              trainingMajor: student.trainingMajor,
              gender: student.gender,
              age: student.age,
              phone: student.phone,
              company: student.company,
              applyDate: student.registerDate || "",
              studentId: student.studentId
            };

            this.studentPool.push(simplifiedStudent);
            // 保持排序
            this.studentPool.sort((a, b) => a.id - b.id);

            this.$message.success(`学员 ${student.name} 已成功退班`);
          } else {
            this.$message.error(result.msg || '退班操作失败');
          }
        } catch (error) {
          console.error('退班操作出错:', error);
          this.$message.error('退班操作失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消退班操作');
      });
    },

    // 批量学员退班
    async handleStudentsBatchExit(students) {
      if (!students || students.length === 0) return;

      this.$confirm(`确定让选中的 ${students.length} 名学员退班？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 构造接口所需参数数组
          const classStudentList = students.map(student => ({
            trainingClassId: this.classId,
            studentId: student.studentId,
            registrationId: student.id,
          }));

          // 调用批量退班接口
          const result = await batchQuit(classStudentList);

          if (result.code === 200) {
            // 处理退班成功的学员
            students.forEach(student => {
              // 从进班列表移除
              const index = this.enteredStudents.findIndex(item => item.id === student.id);
              if (index !== -1) {
                this.enteredStudents.splice(index, 1);
              }

              // 添加到报名库
              const simplifiedStudent = {
                id: student.id,
                name: student.name,
                idCard: student.idCard,
                trainingMajor: student.trainingMajor,
                gender: student.gender,
                age: student.age,
                phone: student.phone,
                company: student.company,
                applyDate: student.registerDate || "",
                studentId: student.studentId
              };

              this.studentPool.push(simplifiedStudent);
            });

            // 保持排序
            this.studentPool.sort((a, b) => a.id - b.id);

            this.$message.success(`成功安排 ${students.length} 名学员退班`);
          } else {
            this.$message.error(result.msg || '批量退班操作失败');
          }
        } catch (error) {
          console.error('批量退班操作出错:', error);
          this.$message.error('批量退班操作失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消批量退班操作');
      });
    },

    // 管理学员信息
    handleManageStudent(student) {
      // 深拷贝学员信息，避免直接修改原数据
      this.currentStudent = JSON.parse(JSON.stringify(student));
      this.studentManageDialogVisible = true;
    },

    // 保存学员信息
    saveStudentInfo() {
      if (!this.currentStudent) return;

      // 更新进班学员列表中的学员信息
      const index = this.enteredStudents.findIndex(item => item.id === this.currentStudent.id);
      if (index !== -1) {
        this.enteredStudents.splice(index, 1, { ...this.currentStudent });
      } else {
        // 如果学员不在进班列表，检查是否在报名库
        const poolIndex = this.studentPool.findIndex(item => item.id === this.currentStudent.id);
        if (poolIndex !== -1) {
          this.studentPool.splice(poolIndex, 1, { ...this.currentStudent });
        }
      }

      this.$message.success('学员信息已保存');
      this.studentManageDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.training-class-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.student-detail {
  max-height: 500px;
  overflow-y: auto;
}

/* 状态样式 */
.status-draft {
  color: #666;
}

.status-pending {
  color: #1890ff;
}

.status-opening {
  color: #faad14;
}

.status-completed {
  color: #52c41a;
}

.status-published {
  color: #1890ff;
}

.status-handed {
  color: #52c41a;
}

.status-full {
  color: #f5222d;
}

.status-almost-full {
  color: #faad14;
}

.status-available {
  color: #52c41a;
}
</style>
